
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author liulingjie
 * @date 20-6-15 下午4:42
 */
public class TcpClient {
    public static boolean isConnect=true;
    public static void main(String[] args) throws IOException {
        Scanner in=new Scanner(System.in);
        String str=null;
        Socket s=null;
        try {
            s = new Socket("127.0.0.1", Integer.parseInt(args[0]));
        } catch (IOException e) {
            isConnect=false;
            e.printStackTrace();
        }
        // 打开输出流
        OutputStream os = s.getOutputStream();
        final InputStream is=s.getInputStream();
//        final ByteArrayOutputStream bos=new ByteArrayOutputStream();

        new Thread(){
            @Override
            public void run() {
                byte[] buffer=new byte[4096];
                int len=0;
                while (true) {
                    if(!isConnect)break;
                    try {
                        len = is.read(buffer, 0, 4096);
                        byte[] buffer1=new byte[len];
                        for (int i=0;i<len;i++){
                            buffer1[i]=buffer[i];
                        }
                        System.out.println("接收消息:");
                        System.out.println(new String(buffer1));
                    } catch (IOException e) {
                    	 isConnect=false;
                    }
                }
            }
        }.start();

        while(true) {
            System.out.println("发送消息：");
            str=in.next();
            os.write(str.getBytes());
            if(str.equals("4") || !isConnect) {
                break;
            }
        }
        os.close();
        is.close();
        s.close();

    }
}

